package es.ats.codington.web.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import es.ats.codington.festival.domain.EventSignUp;
import es.ats.codington.festival.services.EventSignUpService;

/**
 * Servlet implementation class RegisterforEventServlet
 */
@WebServlet("/RegisterforEventServlet")
public class RegisterforEventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterforEventServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");  
		
		HttpSession session=request.getSession(true);
		 
		EventSignUp e=new EventSignUp();
		int idEvent=Integer.parseInt(request.getParameter("idEvent"));
		int idVisitor=(Integer)session.getAttribute("idVisitor");
		e.setIdEvent(idEvent);
		e.setIdVisitor(idVisitor);
		
		EventSignUpService es=new EventSignUpService();
		
		try{
			if(es.checkEventsofVisitor(e)==false){
				if(es.checkSeatsAvailable(e)==true){
					if(es.registerVisitorForNewEvent(e)==1){
					es.updateMinusSeatsAvailableEvent(e);
					ViewEventsofUserServlet view=new ViewEventsofUserServlet();
	    			view.doPost(request, response);

		    		}
					else {
						session.setAttribute("error", "Not registered");
						String actual=(String)session.getAttribute("actual");
			    		RequestDispatcher rd=request.getRequestDispatcher(actual);  
			    		rd.include(request,response);
					}
				}
				else{
					session.setAttribute("error", "Seats NOT available");
		    		String actual=(String)session.getAttribute("actual");
		    		RequestDispatcher rd=request.getRequestDispatcher(actual);  
		    		rd.include(request,response);
					
				}
			}
			else {
				session.setAttribute("error", "Already registered");
				String actual=(String)session.getAttribute("actual");
	    		RequestDispatcher rd=request.getRequestDispatcher(actual);  
	    		rd.include(request,response);
			}
			
		}
			 catch(Exception eee){
			    	eee.getMessage();	
			    }
			           
		}
}
